<template>
  <div>
    <div>
      <el-card class="box-card">
        <div slot="header" class="clearfix">
          <span>预约挂号</span>
          <el-button style="float: right; padding: 3px 0" type="text" @click="addPatient">建档</el-button>
        </div>
        <el-row :gutter="15" class="app">
          <el-form ref="elItemForm" :model="itemData" size="medium" label-width="100px">
            <el-row>
              <el-col :span="6">
                <el-form-item label="姓名" prop="name">
                  <el-autocomplete
                    v-model="itemData.name"
                    :fetch-suggestions="getNameData"
                    placeholder="请输入姓名"
                    @select="getName"
                    clearable
                  ></el-autocomplete>
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="手机号" prop="tel">
                  <el-input
                    placeholder="请输入手机号"
                    clearable
                    :style="{width: '100%'}"
                    v-model="itemData.tel"
                  ></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="出生日期" prop="birth">
                  <el-input
                    placeholder="出生日期"
                    clearable
                    :style="{width: '100%'}"
                    v-model="itemData.birth"
                  ></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="性别" prop="gender">
                  <el-radio-group v-model="itemData.gender">
                    <el-radio
                      v-for="(item, index) in genderInfo"
                      :key="index"
                      :label="item.value"
                    >{{item.label}}
                    </el-radio>
                  </el-radio-group>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="6" v-show="false">
                <el-form-item label="患者ID" prop="id">
                  <el-input placeholder="请输入患者ID" v-model="itemData.id" clearable :style="{width: '100%'}"></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="地址" prop="addr">
                  <el-input
                    placeholder="请输入地址"
                    clearable
                    :style="{width: '100%'}"
                    v-model="itemData.addr"
                  ></el-input>
                </el-form-item>
              </el-col>

              <el-col :span="6">
                <el-form-item label="证件号码" prop="idCard">
                  <el-input
                    placeholder="请输入证件号码"
                    clearable
                    :style="{width: '100%'}"
                    v-model="itemData.idCard"
                  ></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="详细地址" prop="addr">
                  <el-input
                    placeholder="请输入详细地址"
                    clearable
                    :style="{width: '100%'}"
                    v-model="itemData.addr"
                  ></el-input>
                </el-form-item>
              </el-col>
            </el-row>
          </el-form>
        </el-row>
      </el-card>

    </div>
    <!--<el-card class="box-card">
      <div slot="header" class="clearfix" v-show="false">
        科室:
        <el-autocomplete v-model="dept" :fetch-suggestions="deptNameList" @select="chooseDept" p
                         laceholder="选择科室"></el-autocomplete>
        医生:
        <el-autocomplete v-model="doctor" :fetch-suggestions="doctorNameList" @select="chooseDoctor"
                         placeholder="选择医生"></el-autocomplete>
      </div>-->

    <el-table
      ref="table"
      :data="dataList"
      max-height="550"
      @cell-click="edit"
      style="width: 100%;">
      <el-table-column
        fixed
        headerAlign="center"
        align="center"
        prop="userName"
        label="姓名">
      </el-table-column>
      <el-table-column label="排班日期" headerAlign="center">
        <el-table-column v-for="(date,index) in dateList" :key="index"
                         headerAlign="center"
                         :label="date.d + ' ' + date.w"
                         min-width="120">
          <el-table-column label="上午" headerAlign="center" :prop="date.d + 'am'" min-width="100">
            <template slot-scope="scope">
              <div v-if="scope.row[date.d + 'am'] && scope.row[date.d + 'am'].total"
                   :class="'status'+ scope.row[date.d + 'am'].status ">
                <p>名额:{{ scope.row[date.d + 'am'].total }}</p>
                <p>
                  {{ scope.row[date.d + 'am'] | timeFormat }}
                </p>
              </div>
            </template>
          </el-table-column>
          <el-table-column label="下午" headerAlign="center" :prop="date.d + 'pm'" min-width="100">
            <template slot-scope="scope">
              <div v-if="scope.row[date.d + 'pm'] && scope.row[date.d + 'pm'].total"
                   :class="'status'+ scope.row[date.d + 'pm'].status ">
                <p>名额:{{ scope.row[date.d + 'pm'].total }}</p>
                <p>
                  {{ scope.row[date.d + 'pm'] | timeFormat }}
                </p>
              </div>
            </template>
          </el-table-column>
        </el-table-column>
      </el-table-column>
    </el-table>

    <!--</el-card>-->

    <el-dialog :visible.sync="scheduleVisible" title="预约挂号">
      <el-form ref="elForm" :model="targetItem" size="medium" label-width="100px">
        <el-form-item label="预约人" prop="name">
          <p style="margin: 0">{{targetItem.name}}</p>
        </el-form-item>
        <el-form-item label="医生名称" prop="userName">
          <p style="margin: 0">{{targetItem.userName}}</p>
        </el-form-item>
        <el-form-item label="挂号时间" prop="date">
          <!--<el-input v-model="targetItem.date" placeholder="请输入排班时间" readonly clearable :style="{width: '100%'}">
          </el-input>-->
          <p style="margin: 0">{{targetItem.date}}</p>
        </el-form-item>
        <el-form-item label="挂号时间" prop="time">
          <el-time-picker v-model="targetItem.time" is-range format="HH:mm:ss" value-format="HH:mm:ss" step="'00:15'"
                          :style="{width: '100%'}" start-placeholder="开始时间" end-placeholder="结束时间" range-separator="至"
                          clearable></el-time-picker>
        </el-form-item>
        <el-form-item label="班次" prop="noon">
          <p style="margin: 0">{{targetItem.noon| showNoon}}</p>
        </el-form-item>
      </el-form>
      <div slot="footer">
        <el-button @click="close">取消</el-button>
        <el-button type="primary" @click="makeAppt">确定</el-button>
      </div>
    </el-dialog>

    <el-dialog :visible.sync="dialogVisible" @close="onClose" title="快速建档">
      <el-form ref="addForm" :model="addData" :rules="addRules" size="medium" label-width="100px">
        <el-form-item label="姓名" prop="name">
          <el-input v-model="addData.name " placeholder="请输入姓名" clearable :style="{width: '100%'}"></el-input>
        </el-form-item>
        <el-form-item label="性别" prop="gender">
          <el-select v-model="addData.gender " placeholder="请选择性别" clearable :style="{width: '100%'}">
            <el-option v-for="(item, index) in genderOptions" :key="index" :label="item.label"
                       :value="item.value" :disabled="item.disabled"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="手机号码" prop="tel">
          <el-input v-model="addData.tel" placeholder="请输入手机号码" clearable :style="{width: '100%'}"></el-input>
        </el-form-item>
        <el-form-item label="证件号码" prop="idCard ">
          <el-input v-model="addData.idCard " placeholder="请输入证件号码" clearable :style="{width: '100%'}">
          </el-input>
        </el-form-item>
        <el-form-item label="地址" prop="addr">
          <el-input v-model="addData.addr" placeholder="请输入地址" clearable :style="{width: '100%'}"></el-input>
        </el-form-item>
        <el-form-item label="生日" prop="birth ">
          <el-date-picker v-model="addData.birth " format="yyyy-MM-dd " value-format="yyyy-MM-dd "
                          :style="{width: '100%'}" placeholder="请选择生日" clearable></el-date-picker>
        </el-form-item>
        <el-form-item label="备注信息" prop="remark ">
          <el-input v-model="addData.remark " placeholder="请输入备注信息" clearable :style="{width: '100%'}">
          </el-input>
        </el-form-item>
      </el-form>
      <div slot="footer">
        <el-button @click="close">取消</el-button>
        <el-button type="primary" @click="savePatient">确定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
  import {getPatients, addPatients} from "@/api/patient";

  import {savePatient, selectPatient, treatReception} from "@/api/registered";
  import {getDeptList, getDoctorList, getScheduling, editScheduling, makeAppt} from "@/api/scheduling";
  import {getDept, getDeptUsers} from "@/api/dept";
  import {getNextWeek, getDayWeek, formatDate} from "@/utils/date";


  export default {
    name: "setting",
    inheritAttrs: false,
    components: {},
    props: [],
    computed: {},
    filters: {
      timeFormat(p) {
        if (!p.beginTime || !p.endTime) {
          return
        }
        return p.beginTime.substr(0, 5) + "-" + p.endTime.substr(0, 5)
      },
      showNoon(n) {
        return n === "am" ? "上午" : "下午"
      }
    },
    data() {
      return {
        targetItem: {},
        scheduleVisible: false,
        dialogVisible: false,
        dept: "",
        doctor: "",
        name: "",
        dateList: [],
        dataList: [],

        addData: {
          name: "",
          gender: "",
          tel: "",
          idCard: "",
          addr: "",
          birth: '',
          remark: "",
        },

        genderOptions: [{
          "label": "男",
          "value": 1
        }, {
          "label": "女",
          "value": 2
        }],

        addRules: {
          name: [{
            required: true,
            message: '请输入姓名',
            trigger: 'blur'
          }],
          gender: [{
            required: true,
            message: '请选择性别',
            trigger: 'change'
          }],
          tel: [{
            required: true,
            message: '请输入手机号码',
            trigger: 'blur'
          }, {
            pattern: /^1(3|4|5|6|7|8|9)\d{9}$/,
            message: '手机号码格式错误',
            trigger: 'blur'
          }],
          idCard: [],
          addr: [],
          birth: [],
          remark: [],
        },

        patientData: {
          addr: "",
          birth: "",
          consumerId: 0,
          gender: null,
          idCard: "",
          isDefault: true,
          isDel: true,
          name: "",
          remark: "",
          tel: ""
        },

        itemData: {
          id: "",
          name: "",
          gender: 1,
          birth: "",
          addr: "",
          tel: "",
          idCard: "",
          remark: "",
          version: "",
          createDate: "",
          createBy: "sys:admin",
          lastUpdateBy: null,
          lastUpdateDate: "",
          del: false
        },
        itemRules: {
          field101: [],
          field102: [],
          field103: [],
          field104: [],
          field105: [
            {
              required: true,
              message: "请输入姓名",
              trigger: "blur"
            }
          ],
          field106: [],
          field108: [
            {
              required: true,
              message: "性别不能为空",
              trigger: "change"
            }
          ],
          field109: [],

          field111: [
            {
              required: true,
              message: "请选择出生日期",
              trigger: "change"
            }
          ],
          field112: [
            {
              required: true,
              message: "请输入联系人",
              trigger: "blur"
            }
          ],
          field114: [
            {
              required: true,
              message: "请选择",
              trigger: "change"
            }
          ],
          field115: [
            {
              required: true,
              message: "请输入手机号",
              trigger: "blur"
            }
          ]
        },
        genderInfo: [
          {
            label: "男",
            value: 1
          },
          {
            label: "女",
            value: 2
          }
        ]
      };
    },
    watch: {
      dept(val) {
        console.log(val)
      }
    },
    created() {
      window.app = this;
      this.dateList = this.unique(getDayWeek().concat(getNextWeek()));
      this.searchScheduling();
      this.searchDept();
    },
    mounted() {
    },
    methods: {
      unique(arr) {
        let m = {}
        arr = arr.filter(function (a) {
          if (!m[a.d]) {
            m[a.d] = 1
            return true
          }
          return false
        })
        return arr
      },
      makeAppt() {
        let data = {
          "appointmentDate": this.targetItem.date,
          "appointmentKind": 1,
          "appointmentNoon": this.targetItem.noon,
          "beginTime": this.targetItem.beginTime,
          "clinicId": this.targetItem.clinicId,
          "endTime": this.targetItem.endTime,
          "fee": this.targetItem.fee,
          "patientId": this.itemData.id,
          "scheduleId": this.targetItem.id
        }
        makeAppt(data).then(response => {
          if (response.code === 200) {
            this.targetItem.total--;
            this.$message({
              showClose: true,
              message: response.msg,
              type: "success"
            });
            this.searchScheduling();
            this.scheduleVisible = false;
          }
        })
      },
      edit(row, column, cell, event) {
        if (!this.itemData.name) {
          this.$message({
            showClose: true,
            message: "请先选择预约者",
            type: "warning"
          });
          return;
        }
        if (row) {
          console.log(row[column.property]);
          console.log(column.property);
          if (!row[column.property]) {
            row[column.property] = {}
          }
          this.targetItem = row[column.property];

          if (!this.targetItem.total || this.targetItem.total < 1) {
            this.$message({
              showClose: true,
              message: "预约号不足,请选择其他时间",
              type: "warning"
            });
            return;
          }

          this.scheduleVisible = true

          this.targetItem.name = this.itemData.name;
          this.targetItem.patientId = this.itemData.id;
          this.targetItem.userName = row.userName;
          this.targetItem.date = row.date;
          if (!this.targetItem.deptId) {
            this.targetItem.deptId = row.deptId
          }
          if (!this.targetItem.userId) {
            this.targetItem.userId = row.doctorId
          }
          this.targetItem.date = column.property.substr(0, 10)
          this.targetItem.noon = column.property.substr(10)
          if (this.targetItem.beginTime && this.targetItem.endTime) {
            this.targetItem.time = [this.targetItem.beginTime, this.targetItem.endTime]
          }
        }

      },
      searchScheduling() {
        getScheduling({status: 1}).then(response => {
          if (response.code === 200) {
            this.dataList = response.page.list
            let map = {}
            this.dataList.forEach(p => {
              if (!map[p.doctorName]) {
                p.userName = p.doctorName;
                p.dept = p.deptName;
                p.userId = p.doctorId;
                p.dept = p.deptName;
                map[p.doctorName] = p
              }
              // let d = formatDate(p.scheduleDate, "yyyy-MM-dd");
              map[p.doctorName][p.scheduleDate + p.scheduleNoon] = {
                id: p.id,
                clinicId: p.clinicId,
                fee: p.fee,
                total: p.total,
                date: p.scheduleDate,
                noon: p.scheduleNoon,
                beginTime: p.beginTime,
                endTime: p.endTime,
                userId: p.doctorId,
                deptId: p.deptId,
                status: p.status,
              }
            })
            this.dataList = []
            for (let k in map) {
              this.dataList.push(map[k])
            }
          } else {
            this.dataList = []
          }
          if (this.users) {
            this.showSchedule()
          }
        })
      },
      showSchedule() {
        let _that = this;
        this.users.forEach(user => {
          let item = {
            "userId": user.userId,
            "userName": user.niceName,
            "deptId": user.deptId,
            "dept": user.deptName
          }
          let _flag = false;
          _that.dataList.forEach(schedule => {
            if (schedule.userId === user.userId) {
              _flag = true;
              return;
            }
          })
          if (!_flag) {
            _that.dataList.push(item);
            this.dateList.forEach(time => {
              item.date = time.d
              item[time.d + "am"] =
                {
                  status: 0,
                  userId: user.userId,
                  deptId: user.deptId,
                  date: time.d,
                  noon: "am",
                  total: null,
                  beginTime: null,
                  endTime: null,
                  time: null
                }
              item[time.d + "pm"] =
                {
                  status: 0,
                  userId: user.userId,
                  deptId: user.deptId,
                  date: time.d,
                  noon: "pm",
                  total: null,
                  beginTime: null,
                  endTime: null,
                  time: null
                }
            })
          }
        })
      },
      chooseDoctor(item) {
        console.log(item)
      },
      chooseDept(item) {
        console.log(item)
      },
      //挂号
      registered() {
      },
      //查询医生信息
      doctorNameList(query, str) {
        getDoctorList({}).then(response => {
          if (response.code === 200) {
            response.page.list.forEach(user => {
              user.value = user.niceName
            })

            str(response.page.list);
          }
        });
      },

      searchDept() {
        getDept({}).then(response => {
          if (response.code === 200) {
          }
        })
      },
      getUsers() {
        getDeptUsers({"deptId": "" + this.deptId}).then(response => {
          if (response.code === 200) {
            this.users = response.page.list;
            // this.dataList = [];
            this.showSchedule();
          }
        })
      },

      //查询科室信息
      deptNameList(queryString, cb) {
        getDeptList({}).then(response => {
          if (response.code === 200) {
            for (var i = 0; i < response.data.length; i++) {
              response.data[i].value = response.data[i].deptName;
            }

            cb(response.data);
          }
        });
      },
      geTel(tel) {
        var reg = /^(\d{3})\d{4}(\d{4})$/;
        return tel.replace(reg, "$1****$2");
      },
      //查询病人信息select
      getNameData(queryString, cb) {
        selectPatient({name: queryString}).then(response => {
          if (response.code === 200) {
            for (var i = 0; i < response.page.list.length; i++) {
              response.page.list[i].value = response.page.list[i].name + "-"
                + this.geTel(response.page.list[i].tel);
            }

            cb(response.page.list);
          }
        });
      },
      //获取病人名字查询
      getName(val) {
        this.itemData = val;
      },

      onClose() {
        this.$refs["elItemForm"].resetFields();
      },
      close() {
        this.$emit("update:visible", false);
        this.dialogVisible = false
      },
      handelConfirm() {
        let _that = this;
        this.$refs['addForm'].validate(valid => {
          if (!valid) return
          addPatients(this.addData).then(response => {
            if (response.code === 200) {
              this.$message({
                showClose: true,
                message: response.msg,
                type: "success"
              });
              let data = response.data;

              data.value = data.name + "-" + this.geTel(data.tel);

              //TODO:莫名数据丢失,临时解决办法
              setTimeout(function () {
                _that.itemData = data
              }, 500)

              this.dialogVisible = false
            }
          })
        })
      },

      //添加建档
      addPatient() {
        this.dialogVisible = true;
      },
      //保存建档病人信息
      savePatient() {
        savePatient(this.addData).then(response => {
          if (response.code === 200) {
            this.$message({
              showClose: true,
              message: response.msg,
              type: "success"
            });
          }
          this.dialogVisible = false;
        });
      }
    }
  };
</script>

<style lang="scss" scoped>
  .app {
    padding-top: 5px;
    .el-autocomplete {
      width: 100%;
    }
  }

</style>
